<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.search" placeholder="卡名称" style="width: 200px;" clearable class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="卡样式" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag>{{ row.cardStyle | cardStyleEnum }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="卡名称" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.cardName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="卡次数" class-name="status-col" width="100" prop="cardTimes" />
      <el-table-column label="卡分钟" class-name="status-col" width="100" prop="cardMinutes" />
      <el-table-column label="卡的定价" width="150px" align="center" prop="cardPrice" />
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" icon="el-icon-bank-card" @click="handleGenerate(row)">
            生成服务卡
          </el-button>
          <el-button type="primary" size="mini" @click="handleModify(row)">
            修改
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />

    <el-dialog title="编辑虚拟卡" :visible.sync="dialogFormVisible" width="500px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-width="90px">
        <el-form-item label="卡样式" prop="cardStyle">
          <el-select v-model="temp.cardStyle" class="filter-item" placeholder="请选择">
            <el-option v-for="item in cardStyles" :key="item.key" :label="item.name" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="卡名称" prop="vcardName">
          <el-input v-model="temp.cardName" />
        </el-form-item>
        <el-form-item label="次数" prop="vcardTimes">
          <el-input-number v-model="temp.cardTimes" />
        </el-form-item>
        <el-form-item label="分钟" prop="vcardMinutes">
          <el-input-number v-model="temp.cardMinutes" />
        </el-form-item>
        <el-form-item label="卡的定价" prop="vcardPrice">
          <el-input-number v-model="temp.cardPrice" :precision="2" :step="0.01" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():modifyData()">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="生成服务卡信息" :visible.sync="dialogGenerateVisible" width="800px">
      <el-form :model="generateForm" label-width="90px">
        <el-form-item label="卡数量">
          <el-input-number v-model="generateForm.count" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="密码字典">
          <el-input v-model="generateForm.passwordDict" placeholder="每行一个密码" rows="4" />
        </el-form-item>
        <el-form-item label="密码长度">
          <el-input-number v-model="generateForm.passwordLength" :min="1" :max="20" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogGenerateVisible = false">取消</el-button>
        <el-button type="primary" :loading="generateLoading" @click="submitGenerate">生成</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, createType, modifyType, removeType } from '@/api/card/type'
import { generatePhysicalCard } from '@/api/service/card'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const cardStyles = [{
  key: 'NORMAL',
  name: '普通卡'
}, {
  key: 'SILVER',
  name: '白银卡'
}, {
  key: 'GOLD',
  name: '黄金卡'
}, {
  key: 'PLATINUM',
  name: '铂金卡'
}, {
  key: 'BLACK',
  name: '黑金卡'
}, {
  key: 'DIAMOND',
  name: '钻石卡'
}]

const defaultForm = {
  count: 10,
  passwordDict: 'abcdefghijkmnpqrstuvwxyABCDEFGHIJKLMNPQRSTUVWXY3456789@#$%^&*+-=?',
  passwordLength: 8
}

export default {
  name: 'CardType',
  components: { Pagination },
  directives: { waves },
  filters: {
    cardStyleEnum(status) {
      const statusMap = {
        NORMAL: '普通卡',
        SILVER: '白银卡',
        GOLD: '黄金卡',
        PLATINUM: '铂金卡',
        BLACK: '黑金卡',
        DIAMOND: '钻石卡'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 20,
        search: undefined
      },
      cardStyles,
      temp: {
      },
      dialogFormVisible: false,
      dialogStatus: '',
      generateForm: { ...defaultForm },
      generateLoading: false,
      dialogGenerateVisible: false,
      deletePopVisible: false,
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total

        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.current = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createType(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleModify(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'modify'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    modifyData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          modifyType(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      const self = this
      removeType(row).then(() => {
        self.getList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleGenerate(row) {
      this.generateForm = {
        ...defaultForm,
        typeId: row.typeId
      }
      this.generateLoading = false
      this.dialogGenerateVisible = true
    },
    submitGenerate() {
      this.generateLoading = true
      generatePhysicalCard(this.generateForm).then(_ => {
        this.dialogGenerateVisible = false
        this.$message.success('服务卡信息已生成')
        // Reset form
        this.generateForm = { ...defaultForm }
        this.getList()
      })
    }
  }
}
</script>
